package cn.qvtu.web.controller;


import cn.qvtu.web.domain.AjaxResult;
import cn.qvtu.web.domain.Comment;
import cn.qvtu.web.domain.User;
import cn.qvtu.web.service.ICommentService;
import cn.qvtu.web.utility.LoginUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author qvtu
 * @since 2024-04-22
 */
@Controller
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Autowired
    private ICommentService commentService;

    @RequestMapping("/list")
    @ResponseBody
    public PageInfo<Comment> list(Long articleId,@RequestParam(defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,3);
        QueryWrapper<Comment> query = new QueryWrapper<>();
        query.eq("article_id",articleId);
        List<Comment> list = commentService.list(query);
        PageInfo<Comment> page = new PageInfo<>(list);
        return page;
    }

    @Autowired
    private LoginUtils loginUtils;

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(Comment comment, HttpServletRequest request){
        comment.setCreated(new Date()); //实体created 属性修改成Date类型
        comment.setIp(request.getRemoteAddr());
        User loginUser = loginUtils.getLoginUser();
        if(loginUser == null){
            return new AjaxResult(-1,"请先登录");
        }
        comment.setAuthor(loginUser.getUsername());
        try {
            commentService.save(comment);
            return AjaxResult.success();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return  AjaxResult.error();
    }

}




